//
//  ASRConfig.swift
//  GuangLingWuLian
//
//  Created by 杨琴 on 2020/7/20.
//  Copyright © 2020 叁拾叁. All rights reserved.
//语音识别

import UIKit

enum TypeEnum {
    case IFTypeCancel
    case IFTypeStart
    case IFTypeStop
    case IFTypeiniting
    case IFTypeEnd
}

class ASRConfig: NSObject, IFlySpeechRecognizerDelegate {
    
    var result = ""
    var isLast: Bool?
    var type: NSString?
    var resultClosure :  ((TypeEnum,IFlySpeechError?,String) -> Void)?
    var blockOnVolumeChanged : ((Int32) -> Void)?//声音block

    
    
    var iFlySpeechRecognizer : IFlySpeechRecognizer?
    
    static let shared = ASRConfig()
    
    override init() {
        super.init()
        self.inistatCofig()
        
    }
    
    func inistatCofig() {
        
            //创建语音识别对象
        iFlySpeechRecognizer = IFlySpeechRecognizer.sharedInstance();
        //设置识别参数
        iFlySpeechRecognizer?.setParameter("", forKey: IFlySpeechConstant.params())
        //设置为听写模式
        iFlySpeechRecognizer?.delegate = self
        iFlySpeechRecognizer?.setParameter("iat", forKey: IFlySpeechConstant.ifly_DOMAIN())
        //asr_audio_path 是录音文件名，设置value为nil或者为空取消保存，默认保存目录在Library/cache下。
        iFlySpeechRecognizer?.setParameter("iat.pcm", forKey: IFlySpeechConstant.asr_AUDIO_PATH())
    }

     
   // - 识别结束
    func onCompleted(_ errorCode: IFlySpeechError!) {
        
        print("onCompleted:::::录制语音识别的回调");
        if (errorCode.errorCode == 0 ) {
            if (result.count == 0) {
                type = "无识别结果";
            } else {
                type = "识别成功";
            }
            
            
            if let a = isLast,
                a {
                print("调用_completeBlock::::\(String(describing: result)):::::type::::");
                if let c = resultClosure {
                    c(.IFTypeEnd,errorCode,result)
                      }
                // 调用API后清空语音
                result = "";
                isLast = false;
            }
            
        } else {
            result = "";
            isLast = false;
            
            type = "\(errorCode.errorCode)"+(errorCode.errorDesc) as NSString;
            print("语音识别出错:::::::\(String(describing: type))");
        }
        
    }
//    识别结果
    func onResults(_ results: [Any]!, isLast: Bool) {
        
        var resultString = String()
        print("调用onResults::::\(String(describing: results)):::::type::::");

//        NSMutableString *resultString = [[NSMutableString alloc] init];
        let dic:Dictionary<String,Any> = results[0] as! Dictionary<String,Any>;

        for  (_,value) in dic.keys.enumerated() {
            
         resultString = String(format:"%@",value)
            
        }
        
        let resultFromJson:String = ISRDataHelper.string(fromJson: resultString)
        
        self.result = self.result + resultFromJson
        
        self.isLast = isLast;
        
        print(result)
        
        print("调用onResults::::\(String(describing: result)):::::type::::");

        
    }
    // 停止录音
    func onEndOfSpeech() {
        
        
    }
    //开始录音回调
    func onBeginOfSpeech() {
        
        if let c = resultClosure {
            c(.IFTypeiniting,nil,"")
        }
    }
    func onCancel() {
        type = "取消识别"
        iFlySpeechRecognizer?.stopListening(); // 调用此函数会停止录音， 并开始进行语音识别
        iFlySpeechRecognizer?.cancel()// 取消本次会话
    }
    //启动识别服务
    func starIdentify() {
        
        iFlySpeechRecognizer?.startListening();
    }
    //音量回调函数

    func onVolumeChanged(_ volume: Int32) {
        
        if let c = blockOnVolumeChanged {
            c(volume)
        }
        
        
    }
    /**
     * 彻底关闭语音识别
     */
//    #pragma mark - 停止识别服务
    func stopIdentify() {
        print(":::::stopIdentify - 停止识别服务");
        iFlySpeechRecognizer?.stopListening(); // 调用此函数会停止录音， 并开始进行语音识别
        iFlySpeechRecognizer?.cancel()// 取消本次会话
        // [_iFlySpeechRecognizer destroy];         // 销毁识别对象
    }
}
